package com.atguigu03.buffered;

import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * ClassName: BufferedReaderWriterTest
 * Description:
 *
 * @Author liu
 * @Create 2025/3/29 20:07
 * @Version 1.0
 */
public class BufferedReaderWriterTest {
    /*
     * 使用BufferedReader将dbcp_utf-8.txt中的内容显式在控制台上。
     * */
    @Test
    public void test1()  {
        //创建
        BufferedReader br = null;
        try {
            File file = new File("dbcp_utf-8.txt");
            //输入
            br = new BufferedReader(new FileReader(file));
            //读入
            //方式一：read(char[] cBuffer)
            char[] cBuffer = new char[1024];
            int len;
            while((len =br.read(cBuffer)) != -1){
//                //法1：
//                for (int i = 0; i < len; i++) {
//                    System.out.print(cBuffer[i]);
//                }
                //法2：
                String str = new String(cBuffer,0,len);
                System.out.print(str);
            }

//            //方式二：readLine()
//            String data;
//            while((data = br.readLine()) !=null){
//                System.out.println(data+"\n");
//            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(br !=null){
                    br.close( );
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
    /*
     * 使用BufferedReader和BufferedWriter实现文本文件的复制
     *
     * 注意：开发中，还是需要使用try-catch-finally来处理流的异常。
     * */

    @Test
    public void test2(){
        BufferedReader br=null;
        BufferedWriter bw=null;
        try {
            File file1 = new File("dbcp_utf-8.txt");
            File file2 = new File("dbcp_utf-8_copy.txt");

            br = new BufferedReader(new FileReader(file1));
            bw = new BufferedWriter(new FileWriter(file2));

            //文件的读入
            String data;
            while((data = br.readLine()) !=null){
                bw.write(data);
                bw.newLine();//换行
                bw.flush();///刷新的方法。每当调用此方法时，就会主动的将内存中的数据写出到磁盘文件中.
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(bw !=null){
                    bw.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if(br !=null){
                    br.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
